package com.zlsy.secondtime.threadcoreknowledge.stopthreads;

import lombok.extern.slf4j.Slf4j;

/**
 * @author zhouliang
 * @date 2020/5/15 9:55
 * catch 了InterruptedException后优先选择：在方法签名中抛出异常
 * <p>
 * 那么run就会强制的try\catch
 */
@Slf4j
public class RightWayStopThreadInProd implements Runnable {

    @Override
    public void run() {
        while (true) {
            try {
                throwInMethod();
            } catch (InterruptedException e) {
                //记录日志
                log.error("线程被中断:{}", e.getMessage());
                //退出程序
                break;
            }
        }
        System.out.println(1);
    }

    private void throwInMethod() throws InterruptedException {
        Thread.sleep(1000);
    }

    public static void main(String[] args) throws InterruptedException {
        RightWayStopThreadInProd r = new RightWayStopThreadInProd();
        Thread thread = new Thread(r);
        thread.start();
        Thread.sleep(500);
        thread.interrupt();
    }
}